<script setup>
import { inject, ref } from "vue";
import {
  addressCreateApi,
  areaListApi,
  addressDetailApi,
  addressDelApi,
  addressDefaultApi,
} from "@/services/address";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { address } from "@/utils/address";
import { useaddressStore } from "@/stores/address";

const dateobj = useaddressStore();

onLoad((e) => {
  areaListFun();
  fromdate.value.address_id = e.address_id;
  addressDetailFun();
  type.value = e.type ? e.type : null;
});

// const selectaddress = ref(null);

// const changeaddress = (address) => {
//   selectaddress.value = address;
// };
const type = ref(null);
const fromdate = ref({
  address_id: "",
  real_name: "",
  is_default: 1,
  area: [],
});
const switchValue = ref(true);

// 地区
const show = ref(false);
const columns = ref([]);

const province = ref([]);
const city = ref([]);
const county = ref([]);
const addressdata = ref([]);
const selectaddress = ref("");
// 获取地区数据
async function areaListFun() {
  //发送请求
  let res = await areaListApi();
  addressdata.value = res.data;
  province.value = res.data;
  city.value = res.data[0].sub;
  county.value = res.data[0].sub[0].sub;
  // res.data.map((item) => {
  //   province.value.push(item);
  // });
  // res.data[0].sub.forEach((item) => {
  //   city.value.push(item.name);
  // });
  // res.data[0].sub[0].sub.forEach((item) => {
  //   county.value.push(item.name);
  // });
  columns.value.push(province.value, city.value, county.value);
}

const uPickerRef = ref(null);
const changeHandler = (e) => {
  const { columnIndex, value, values, index, indexs, code } = e;

  city.value = [];
  county.value = [];
  let lenghts = addressdata.value[indexs[0]].sub.length;
  if (
    addressdata.value &&
    addressdata.value[indexs[0]].sub &&
    !addressdata.value[indexs[0]].sub[indexs[1]]
  ) {
    city.value =
      addressdata.value &&
      addressdata.value[indexs[0]] &&
      addressdata.value[indexs[0]].sub;
    county.value =
      addressdata.value &&
      addressdata.value[indexs[0]] &&
      addressdata.value[indexs[0]].sub[lenghts - 1] &&
      addressdata.value[indexs[0]].sub[lenghts - 1].sub;
  } else {
    city.value =
      addressdata.value &&
      addressdata.value[indexs[0]] &&
      addressdata.value[indexs[0]].sub;
    county.value =
      addressdata.value &&
      addressdata.value[indexs[0]] &&
      addressdata.value[indexs[0]].sub[indexs[1]] &&
      addressdata.value[indexs[0]].sub[indexs[1]].sub;
  }

  // if (
  //   addressdata.value &&
  //   addressdata.value[indexs[0]] &&
  //   addressdata.value[indexs[0]].sub[indexs[1]] &&
  //   addressdata.value[indexs[0]].sub[indexs[1]].sub
  // ) {
  //   index[0] = 0;
  //   indexs[1] = 0;
  // }

  // addressdata.value[indexs[0]].sub.forEach((element) => {
  //   city.value.push(element.name);
  // });
  // addressdata.value[indexs[0]].sub[indexs[1]].sub.forEach((element) => {
  //   county.value.push(element.name);
  // });
  columns.value = [];
  columns.value.push(province.value, city.value, county.value);
};
// 选择确定
const confirm = (e) => {
  let arr = address(addressdata.value, e.indexs);
  selectaddress.value =
    e.value[0].name + "/" + e.value[1].name + "/" + e.value[2].name;
  fromdate.value.area = arr;
  show.value = false;
};

// 地址详情
async function addressDetailFun() {
  fromdate.value.address_id ? fromdate.value.address_id : 0;
  if (fromdate.value.address_id > 0) {
    let res = await addressDetailApi(fromdate.value);
    fromdate.value = {
      real_name: res.data.real_name,
      phone: res.data.phone,
      detail: res.data.detail,
      address_id: res.data.address_id,
      is_default: res.data.is_default,
      area: res.data.area,
      province: res.data.province,
      province_code: res.data.province_code,
      city: res.data.city,
      city_code: res.data.city_code,
      district: res.data.district,
      district_code: res.data.district_code,
      area: [],
    };
    switchValue.value = fromdate.value.is_default == "1" ? true : false;
    selectaddress.value =
      res.data.province + "/" + res.data.city + "/" + res.data.district;
  }
}

// 设置默认
const addressDefaultFun = async () => {
  try {
    let res = await addressDefaultApi({
      address_id: fromdate.value.address_id,
    });
    if (res.code === 200) {
    }
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
    });
  }
};

// 添加/编辑地址
async function addressCreateFun() {
  const area = [];
  area.push(
    { name: fromdate.value.province, code: fromdate.value.province_code },
    { name: fromdate.value.city, code: fromdate.value.city_code },
    { name: fromdate.value.district, code: fromdate.value.district_code }
  );

  fromdate.value.area =
    fromdate.value.area.length > 0 ? fromdate.value.area : area;

  // 发送请求

  try {
    let res = await addressCreateApi(fromdate.value);
    if (res.code === 200) {
      if (type.value == "add" || type.value == "addup") {
        fromdate.value.province = fromdate.value.area[0].name;
        fromdate.value.city = fromdate.value.area[1].name;
        fromdate.value.district = fromdate.value.area[2].name;
        dateobj.setaddress(JSON.stringify(res.data));
        // addressDefaultFun();
        // // 4. 返回上一页面
        uni.showToast({
          title: "提交成功",
          icon: "none",
        });
        uni.navigateBack({
          delta: 1, // 返回的页面数
        });
      } else {
        // addressDefaultFun();
        // // 4. 返回上一页面
        uni.navigateBack({
          delta: 1, // 返回的页面数
        });
      }
    }
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
    });
  }
}

const changefun = (e) => {
  fromdate.value.is_default = e ? 1 : 0;
};
// 返回A页
function goPageA(josn) {
  // 1. 获取当前页面栈实例（此时最后一个元素为当前页）
  let pages = getCurrentPages();

  // 2. 上一页面实例
  // 注意是length长度，所以要想得到上一页面的实例需要 -2
  // 若要返回上上页面的实例就 -3，以此类推
  let prevPage = pages[pages.length - 2];

  // 3. 给上一页面实例绑定getValue()方法和参数（注意是$vm）
  prevPage.$vm.getValue(josn);

  // 4. 返回上一页面
  uni.navigateBack({
    delta: 1, // 返回的页面数
  });
}

// 删除
const showDelete = ref(false);
const closeDelete = () => {
  showDelete.value = false;
};
async function addressDelete() {
  // 发送请求
  let res = await addressDelApi(fromdate.value);
  if (res.code === 200) {
    uni.navigateBack({
      delta: 1, // 返回的页面数
    });
  }
}

const addressconfirm = (value) => {
  // area.push(
  //   { name: fromdate.value.province, code: fromdate.value.province_code },
  //   { name: fromdate.value.city, code: fromdate.value.city_code },
  //   { name: fromdate.value.district, code: fromdate.value.district_code }
  // );
  fromdate.value.real_name = value.name;
  fromdate.value.detail = value.print_addr;
  fromdate.value.phone = value.mobile;
  let sbzt = false;

  addressdata.value.forEach((element, index) => {
    if (element.name === value.province) {
      element.sub.forEach((element1, index1) => {
        if (element1.name === value.city) {
          element1.sub.forEach((element2, index2) => {
            if (element2.name === value.district) {
              sbzt = true;
              fromdate.value.province = element.name;
              fromdate.value.province_code = element.code;
              fromdate.value.city = element1.name;
              fromdate.value.city_code = element1.code;
              fromdate.value.district = element2.name;
              fromdate.value.district_code = element2.code;

              selectaddress.value =
                fromdate.value.province +
                "/" +
                fromdate.value.city +
                "/" +
                fromdate.value.district;
            } else {
            }
          });
        } else {
        }
      });
    } else {
    }
  });
  if (!sbzt) {
    uni.showToast({
      title: "地区识别失败,请选择",
      icon: "none",
    });
  }

  // fromdate.value.province = value.name;
  // fromdate.value.real_name = value.name;
};
</script>

<template>
  <view class="upgrade">
    <u--form>
      <view class="user-form">
        <u-form-item
          required="true"
          label="联系人姓名"
          prop="real_name"
          borderBottom
          ref="item1"
        >
          <u--input
            v-model="fromdate.real_name"
            border="none"
            placeholder="请填写"
          ></u--input>
        </u-form-item>
        <u-form-item
          required="true"
          label="手机号码"
          prop="phone"
          borderBottom
          ref="item1"
        >
          <u--input
            v-model="fromdate.phone"
            border="none"
            placeholder="请填写"
          ></u--input>
        </u-form-item>

        <u-form-item
          required="true"
          label="选择区域"
          prop="area"
          borderBottom
          ref="item1"
        >
          <view class="list-index-right">
            <up-picker
              :show="show"
              ref="uPickerRef"
              :columns="columns"
              keyName="name"
              @confirm="confirm"
              @change="changeHandler"
              @cancel="show = false"
            ></up-picker>
            <text
              @click="show = true"
              :class="selectaddress ? 'selectaddress-text' : ''"
              >{{ selectaddress ? selectaddress : "请选择省/市/区" }}</text
            >
            <!-- <sh-address @change="changeaddress">
              {{
                selectaddress
                  ? selectaddress.province +
                    "/" +
                    selectaddress.city +
                    "/" +
                    selectaddress.area
                  : "请选择省/市/区"
              }}
            </sh-address> -->
            <u-icon name="arrow-right" color="#8C8C8C" size="16"></u-icon>
          </view>
        </u-form-item>
        <u-form-item required="true" label="详细地址" borderBottom ref="item1">
          <u--input
            v-model="fromdate.detail"
            border="none"
            placeholder="请输入单元、楼层、房号"
          ></u--input>
        </u-form-item>

        <u-form-item label="默认地址" borderBottom ref="item1">
          <view class="switch-v">
            <up-switch
              v-model="switchValue"
              activeColor="#F3498B"
              @change="changefun"
            ></up-switch>
          </view>
        </u-form-item>
      </view>

      <view class="copy-k">
        <u-form-item labelWidth="150" label="智能填写" borderBottom ref="item1">
        </u-form-item>
        <Winglau14-address-auto-parse
          @confirm="addressconfirm"
        ></Winglau14-address-auto-parse>
      </view>
    </u--form>
  </view>

  <view class="foodr-bt">
    <view class="bt-next" @click="showDelete = true" v-if="fromdate.address_id"
      >删除</view
    >
    <view class="bt-sbuit" @click="addressCreateFun"> 保存 </view>
  </view>

  <!-- 拒绝支付弹框 -->
  <view class="password_show">
    <u-popup
      :show="showDelete"
      mode="center"
      round="10"
      @close="close"
      @open="open"
    >
      <view class="productGift">
        <view class="popup-content-title">删除地址</view>
        <view class="popup-content-item">确认要删除该地址吗？</view>
        <view class="popup-content-box">
          <view class="popup-content-bt">
            <view class="popup-content-qx" @click="closeDelete">取消</view>
            <view class="popup-content-cl" @click="addressDelete">确定</view>
          </view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<style lang="scss" scoped>
@import "./index.scss";
</style>
